<?php

class ModelStoryContent extends Model {

      /**
       * 每页显示的行数
       */
      public function getLimit() {
            $limit = 20;
            return $limit;
      }

      /**
       * 获取总页数
       */
      public function count($storyId) {
            $sql = sprintf("SELECT count(0) AS num FROM `%s` WHERE `story_id` = '%d'",
                  "story_content",
                  (int)$storyId
            );
            $query = $this->db->query($sql);
            if ($row = $query->row) {
                  return $row['num'];
            }
            return 0;
      }

      /**
       * 获取列表
       */
      public function list($categoryId, $page = 1) {
            $limit = $this->getLimit();
            $start = ($page-1)*$limit;
            $query = $this->db->query(sprintf("SELECT s.story_id, sc.title, sc.content FROM `%s` AS sc 
                  INNER JOIN `%s` AS s ON sc.story_id = s.story_id AND sc.page_id = 1
                  WHERE s.category_id = '%d' ORDER BY s.date_added DESC LIMIT %d, %d",
                  "story_content",
                  "story",
                  (int)$categoryId,
                  $start,
                  $limit
            ));
            return $query->rows;
      }

      /**
       * 获取详情
       */
      public function get($storyId, $page = 0) {
            $query = $this->db->query(sprintf("SELECT * FROM `%s` WHERE story_id = '%d' AND page_id = '%d'",
                  "story_content",
                  (int)$storyId,
                  (int)$page
            ));
            if ($row = $query->row) {
                  if ($page <= 1) {
                        $this->db->query(sprintf("UPDATE `%s` SET `num_clicks` = `num_clicks` + 1 WHERE `story_id` = '%d'",
                              "story",
                              (int)$storyId
                        ));
                  }
                  return $row;
            }
            return null;
      }

      /**
       * 获取阅读量大的故事
       */
      public function top($categoryId, $limit = 5) {
            $query = $this->db->query(sprintf("SELECT s.story_id, sc.title, sc.content FROM `%s` AS sc 
                  INNER JOIN `%s` AS s ON sc.story_id = s.story_id AND sc.page_id = 1
                  WHERE s.category_id = '%d' ORDER BY s.num_clicks DESC LIMIT %d, %d",
                  "story_content",
                  "story",
                  (int)$categoryId,
                  0,
                  $limit
            ));
            return $query->rows;
      }
}